<?php

namespace App\Service\TraitService;
use App\Service\Code\Normal;
use Xxtime\Flysystem\Aliyun\OssAdapter;
use League\Flysystem\Filesystem;
use finfo;
use App\Service\AppService\SystemCacheConfigService;

/**
 * 阿里云文件上传服务
 * @author chenshubo
 */
trait AliYunOssFileUploadTrait
{
    /**
     * 文件文件流
     * @param string $contents
     * @param string $fileName
     * @return mixed
     */
    public function uploadByContents( string $contents,string $filePath)
    {
        try {
            
            $config = SystemCacheConfigService::instance()->getCacheInfoBySystemCode('oss');
            // 配置
            $adapter = new OssAdapter([
                'accessId'       => $config['oss_key_id'],
                'accessSecret'   => $config['oss_key_secret'],
                'bucket'         => $config['oss_bucket'],
                'endpoint'       => $config['oss_endpoint'],
                'timeout'        => 3600,
                'connectTimeout' => 10,
            ]);
            $filesystem = new Filesystem($adapter);
            
            // 设置属性
            // 如设置了Content-Type，则可以不指定路径的后缀 (即$filePath可以不包含.jpg等后缀名)
            $fInfo = new finfo(FILEINFO_MIME_TYPE);
            $mimeType = $fInfo->buffer($contents);
            $wconfig = [
                "Content-Type" => $mimeType
            ];
            
            // 上传
            if (!$filesystem->write($filePath, $contents, $wconfig)) {
                return Normal::returnCode(Normal::FAIL,"文件处理失败");
            }
            
            // 获取信息
            $raw = $adapter->supports->getFlashData();
            if( empty($raw['oss-request-url']) ) {
                return Normal::returnCode(Normal::FAIL,"文件处理oss-request-url地址获取失败");
            }
            
            return Normal::returnCode(Normal::SUC,"处理完成",[
                'url'   => $config['url'].'/'.$filePath
            ]);
        } catch ( \Throwable $th ) {
            return Normal::returnCode(Normal::FAIL,"文件处理异常[{$th->getMessage()},{$th->getFile()},{$th->getLine()}]");
        }
    }
}